package com.twan.kotlinbase.app

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jaeger.library.StatusBarUtil
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.tencent.mm.opensdk.utils.Log
import com.twan.kotlinbase.R
import com.twan.kotlinbase.bean.UploadPic
import com.twan.kotlinbase.event.TakePhotoEvent
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.pop.AddPicPopup
import com.twan.kotlinbase.util.GlideUtils
import com.twan.kotlinbase.widgets.MySearchView
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import kotlinx.android.synthetic.main.viewstub1_zhibo.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rxhttp.awaitString
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse
import rxhttp.wrapper.param.upload

//如果你使用databinding,请继承这个基类,用法不变
abstract class BaseDataBindingFragment<T:ViewDataBinding> : Fragment() {
    lateinit var mActivity: Activity
    lateinit var mContext: Context
    lateinit var mFragment: Fragment
    protected lateinit var mBinding: T
    /**
     * 是否对用户可见
     */
    protected var mIsVisible = false

    /**
     * 是否加载完成
     * 当执行完oncreatview,View的初始化方法后方法后即为true
     */
    protected var mIsPrepare = false

    @JvmField @BindView(R.id.back) var back: ImageButton? = null
    @JvmField @BindView(R.id.ib_login) var ib_login: ImageButton? = null
    @JvmField @BindView(R.id.tv_back_text) var tv_back_text: TextView? = null
    @JvmField @BindView(R.id.ib_right) var ib_right: ImageButton? = null
    @JvmField @BindView(R.id.title) var title: TextView? = null
    @JvmField @BindView(R.id.tv_right) var tv_right: TextView? = null
    @JvmField @BindView(R.id.toolbar) var toolbar: Toolbar? = null
    @JvmField @BindView(R.id.search_view) var searchView: MySearchView? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mBinding = DataBindingUtil.inflate(inflater,getLayoutId(),container, false)
        ButterKnife.bind(this,mBinding.root)
        EventBus.getDefault().register(this)
        getBundleData(arguments)
        initTitle()
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mFragment=this
        initView(view, savedInstanceState)
        mIsPrepare = true
    }

    fun whiteStatusBar(){
        StatusBarUtil.setColor(mActivity, resources.getColor(R.color.white), 0)
        toolbar?.setBackgroundColor(resources.getColor(R.color.white))
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as Activity
        mContext = context
    }

    protected fun initTitle() {
        back?.visibility = View.VISIBLE
        title?.visibility = View.VISIBLE
        ib_login?.visibility = View.GONE
        tv_back_text?.visibility = View.GONE
        title?.text = getString(R.string.app_name)
        ib_right?.visibility = View.GONE
        tv_right?.visibility = View.GONE
    }

    /**
     * 该抽象方法就是 onCreateView中需要的layoutID
     *
     * @return
     */
    protected abstract fun getLayoutId():Int

    /**
     * 该抽象方法就是 初始化view
     *
     * @param view
     * @param savedInstanceState
     */
    protected abstract fun initView(view: View?, savedInstanceState: Bundle?
    )

    /**
     * 执行数据的加载
     */
    protected fun getBundleData(arguments: Bundle?) {}

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        mIsVisible = isVisibleToUser
        if (isVisibleToUser) {
            onVisibleToUser()
        }
    }

    /**
     * 用户可见时执行的操作
     */
    protected fun onVisibleToUser() {
        if (mIsPrepare && mIsVisible) {

        }
    }

    /**
     * 懒加载，仅当用户可见切view初始化结束后才会执行
     */
    open fun reqData() {}

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    //处理图片,视频部分
    var mCurrTakePhotoPath = ""
    var uploadType=1 //1相册多选,2视频多选,3单个视频或者图片
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == AddPicPopup.REQUEST_CODE_CHOOSE && resultCode == Activity.RESULT_OK) {
            var selected = Matisse.obtainResult(data)
            selected.forEach {
                var realpath = UriUtils.uri2File(it).absolutePath
                mCurrTakePhotoPath=realpath
                LogUtils.e("选择路径: $realpath")
                upload(realpath)
            }
        } else if (requestCode == AddPicPopup.REQUEST_CODE_TAKE_PHOTO && resultCode == Activity.RESULT_OK){
            upload(mCurrTakePhotoPath)
            LogUtils.e("拍照路径: $mCurrTakePhotoPath")
        } else if (requestCode == AddPicPopup.REQUEST_VIDEO_CAPTURE && resultCode == Activity.RESULT_OK) {
            upload(mCurrTakePhotoPath)
            LogUtils.e("视频路径: $mCurrTakePhotoPath")
        }
    }

    //图片选择
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun dataEvent(selected: TakePhotoEvent) {
        mCurrTakePhotoPath = selected.path
        LogUtils.e("拍照或者视频路径:$mCurrTakePhotoPath")
    }

    open fun upload(filepath:String){
        RxHttpScope().launch {
            if (!::loadingPopup.isInitialized) {
                loadingPopup = XPopup.Builder(mActivity).dismissOnTouchOutside(false).asLoading("正在加载中")
            }
            if (loadingPopup.isDismiss) loadingPopup.show()
            var req= RxHttp.postForm("cos/upload").connectTimeout(60000).
            readTimeout(60000).writeTimeout(60000).addFile("file",filepath).upload(this)
            {
                val currentProgress = it.progress //当前进度 0-100
                val currentSize = it.currentSize  //当前已上传的字节大小
                val totalSize = it.totalSize      //要上传的总字节大小
                Log.e("currentProgress",""+currentProgress);
                Log.e("currentSize",""+currentSize);
            }.toResponse<String>().await()
            if (loadingPopup.isShow) loadingPopup.dismiss()
            uploadCallback(req)
            LogUtils.e("文件上传成功:$req")
        }
    }

    open fun uploadCallback(url:String){

    }






    //图片或者视频多选
    var uploadPics= mutableListOf<UploadPic>().apply { this.add(UploadPic(true)) }
    var uploadVideos= mutableListOf<UploadPic>().apply { this.add(UploadPic(true)) }
    var uploadAnlis= mutableListOf<UploadPic>().apply { this.add(UploadPic(true)) }
    lateinit var loadingPopup: BasePopupView
    /**
     * uploadType2 1相册多选,2视频多选,4案例多选 只传1,2,4
     */
    fun initRvMultiPicOrVideo(recyclerView: RecyclerView, uploadType2:Int=1){
        var datas = if (uploadType2==1) uploadPics else if (uploadType2==2) uploadVideos else uploadAnlis
        recyclerView.layoutManager= GridLayoutManager(mActivity,4)
        recyclerView.adapter=object : BaseQuickAdapter<UploadPic, BaseViewHolder>(R.layout.item_upload_img,datas.asReversed()){
            override fun convert(holder: BaseViewHolder, item: UploadPic) {
                var iv_close=holder.getView<ImageView>(R.id.iv_close)
                var iv_pic=holder.getView<ImageView>(R.id.iv_pic)
                iv_close.visibility=if (item.isAddBtn) View.GONE else View.VISIBLE
                GlideUtils.load(mActivity,iv_pic,item.filepath,if (uploadType2==2) R.mipmap.upload_video else R.mipmap.upload_pic)

                iv_close.setOnClickListener {
                    datas.remove(item)
                    notifyDataSetChanged()
                }
                iv_pic.setOnClickListener {
                    if(!item.isAddBtn) return@setOnClickListener
                    if (datas.size == 10) {
                        ToastUtils.showShort("最多只能选择9张")
                        return@setOnClickListener
                    }
                    uploadType=uploadType2
                    if (uploadType2==1) {
                        XPopup.Builder(mActivity).asCustom(AddPicPopup(mActivity,mFragment, maxSelect = 10-datas.size)).show()
                    } else if (uploadType2==2){
                        XPopup.Builder(mActivity).asCustom(AddPicPopup(mActivity,mFragment, maxSelect = 10-datas.size,isTakePhoto = false,mimeType = MimeType.ofVideo())).show()
                    } else if (uploadType2==4){ //案例
                        XPopup.Builder(mActivity).asCustom(AddPicPopup(mActivity,mFragment, maxSelect = 10-datas.size)).show()
                    }
                }
            }

        }
    }
    //清空图片或者视频的数据
    fun clear(uploadType2:Int=1){
        if (uploadType2==1){
            uploadPics.clear()
            uploadPics.add(UploadPic(true))
        } else if (uploadType2==2) {
            uploadVideos.clear()
            uploadVideos.add(UploadPic(true))
        } else {
            uploadAnlis.clear()
            uploadAnlis.add(UploadPic(true))
        }
    }
    //图片
    fun getPicsUrl():String{
        return getPinjieUrl(uploadPics)
    }
    //视频
    fun getVideosUrl():String{
        return getPinjieUrl(uploadVideos)
    }
    //案例
    fun getAnliUrl():String{
        return getPinjieUrl(uploadAnlis)
    }

    fun getPinjieUrl(datas:MutableList<UploadPic>):String{
        var url=""
        if (datas.size == 1) return ""
        else {
            datas.forEach {
                if (!it.isAddBtn) url += (it.filepath + ",")
            }
        }
        if (url.isNotEmpty() && url.last() == ',') url = url.dropLast(1)
        if (url.isNotEmpty() && url.first() == ',') url = url.drop(1)
        return url
    }

}